<!DOCTYPE html>
<html>
  <head>
    <link type="text/css" rel="stylesheet" href="css/material-icons.css"/>
    <!--Import materialize.css-->
    <link type="text/css" rel="stylesheet" href="css/materialize.min.css"  media="screen,projection"/>
    <title>Zone Status Dashboard</title>

    <!--Let browser know website is optimized for mobile-->
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <style>
    nav.clean{
        background: none;
        box-shadow: none;
    }

    .breadcrumb:before {
        color: rgba(0,0,0,0.7);
    }

    .breadcrumb, .breadcrumb:last-child {
       color: rgba(0,0,0,1);
    }
    </style>

  </head>
  <body>
  <div class="container">
    <div class="section">
      <div class="row center">
        <span id="uptime"></span>
      </div>
      <div class="row">
        <div class="col m8 s12">
          <a href="pool_status.html" class=" blue-grey-text">
          <div class="card small">
            <div class="card-content">
              <span class="card-title" id="resource-caption"><i class="material-icons blue-grey-text darken-2">cloud_queue</i></span>
              <div class="row">
                <div class="col m3 s12">
                  <canvas id="pool_canvas" height="320px"></canvas>
                </div>
                <div class="col m3 s12">
                  <canvas id="cell_canvas" height="320px"></canvas>
                </div>
                <div class="col m3 s12">
                  <canvas id="instance_canvas" height="320px"></canvas>
                </div>
                <div class="col m3 s12">
                  <canvas id="disk_canvas" height="320px"></canvas>
                </div>
              </div>
            </div>

          </div>
          </a>
        </div>
        <div class="col m4 s6">
          <div class="card small">
            <div class="card-content">
              <span class="card-title" id="core-caption"><i class="material-icons blue-grey-text">memory</i></span>
              <div>
                <canvas id="cpu_canvas" height="180px"></canvas>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="row">
        <div class="col m3 s6">
          <div class="card small">
            <div class="card-content">
              <span class="card-title" id="memory-caption"><i class="material-icons blue-grey-text">sd_card</i></span>
              <div>
                <canvas id="memory_canvas" height="280px"></canvas>
              </div>
            </div>
          </div>
        </div>
        <div class="col m9 s12">
          <div class="card small">
            <div class="card-content">
              <span class="card-title" id="io-caption"><i class="material-icons blue-grey-text">storage</i></span>
              <div>
                <canvas id="io_canvas" height="80px"></canvas>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="row">
      </div>
    </div>
  </div>

  <!--JavaScript at end of body for optimized loading-->
  <script type="text/javascript" src="js/materialize.min.js"></script>
  <script type="text/javascript" src="js/jquery-3.3.1.min.js"></script>
  <script type="text/javascript" src="js/Chart.bundle.min.js"></script>
  <script type="text/javascript" src="js/nano.js"></script>
  <script>
    N.ValidateSession();
    var texts = N.GetTexts();
    // $('#zone-caption').text(texts.get(N.TagZone));
    $('#resource-caption').append(texts.get(N.TagResourceUsage));
    $('#core-caption').append(texts.get(N.TagCoreUsage));
    $('#memory-caption').append(texts.get(N.TagMemoryUsage));
    $('#io-caption').append(texts.get(N.TagIOMeter));

    M.AutoInit();
    //pool doughnut
    var poolChart = new Chart($("#pool_canvas"),{
        type: "doughnut",
        data: {
          labels: [ texts.get(N.TagDisable), texts.get(N.TagEnable)],
          datasets: [
            {
              backgroundColor: ['#9e9e9e', '#03a9f4'],
            }
          ],
        },
  			options: {
          cutoutPercentage: 70,
  				legend: {
            display: false,
  					// position: 'right',
  				},
  				title: {
  					display: true,
  					text: texts.get(N.TagComputePool)
  				}
  			}
    });
    //cell doughnut
    var cellChart = new Chart($("#cell_canvas"),{
        type: "doughnut",
        data: {
          labels: [ texts.get(N.TagOffline), texts.get(N.TagOnline)],
          datasets: [
            {
              backgroundColor: ['#9e9e9e', '#4caf50'],
            }
          ],
        },
        options: {
          cutoutPercentage: 70,
          legend: {
            display: false,
            // position: 'right',
          },
          title: {
            display: true,
            text: texts.get(N.TagCell)
          }
        }
    });
    //instance doughnut
    var instanceChart = new Chart($("#instance_canvas"),{
        type: "doughnut",
        data: {
          labels: [ texts.get(N.TagStopped), texts.get(N.TagRunning), texts.get(N.TagLost), texts.get(N.TagMigrate)],
          datasets: [
            {
              backgroundColor: ['#9e9e9e', '#2196f3', "#ff9800", "#9e9e9e"],
            }
          ],
        },
        options: {
          cutoutPercentage: 70,
          legend: {
            display: false,
            // position: 'right',
          },
          title: {
            display: true,
            text: texts.get(N.TagInstance)
          }
        }
    });
    var diskChart = new Chart( $("#disk_canvas"), {
      type: "doughnut",
      data: {
        labels: [ texts.get(N.TagAvailable), texts.get(N.TagUsed)],
        datasets: [
          {
            backgroundColor: ['#bbdefb', '#2196f3'],
          }
        ],
      },
      options: {
        cutoutPercentage: 70,
        legend: {
          display: false,
          // position: 'right',
        },
        title: {
          display: true,
          text: texts.get(N.TagDisk)
        }
      }
    });
    //cpu canvas
    var cpuChart = new Chart($("#cpu_canvas"), {
        type: "bar",
        data: {
          labels: ["10", "8", "6", "4", "2", "0"],
          datasets: [
            {
              label: texts.get(N.TagUsed),
              stack: 'Stack 0',
              backgroundColor: '#66bb6a',
            },
            {
              label: texts.get(N.TagAvailable),
              stack: 'Stack 0',
              backgroundColor: '#e8f5e9',
            }
          ]
        },
        options: {
          legend: {
            display: false,
          },
          scales: {
  					xAxes: [{
              display: false
  					}],
            yAxes: [{
                stacked: true
            }]
  				}
        }
    });
    //memory canvas
    var memoryChart = new Chart( $("#memory_canvas"), {
        type: "bar",
        data: {
          labels: ["10", "8", "6", "4", "2", "0"],
          datasets: [
            {
              label: texts.get(N.TagUsed),
              stack: 'Stack 0',
              backgroundColor: '#42a5f5',
            },
            {
              label: texts.get(N.TagAvailable),
              stack: 'Stack 0',
              backgroundColor: '#e3f2fd',
            }
          ]
        },
        options: {
          legend: {
            display: false,
          },
          scales: {
  					xAxes: [{
              display: false
  					}],
            yAxes: [{
                stacked: true
            }]
  				}
        }
    });

    //io
    var ioChart = new Chart( $("#io_canvas"), {
        type: "bar",
        data: {
          labels: ["16", "14", "12", "10", "8", "6", "4", "2", "0"],
          datasets: [
            {
              label: texts.get(N.TagRead),
              backgroundColor: '#90caf9',
            },
            {
              label: texts.get(N.TagWrite),
              backgroundColor: '#b0bec5',
            },
            {
              label: texts.get(N.TagReceive),
              backgroundColor: '#b39ddb',
            },
            {
              label: texts.get(N.TagSend),
              backgroundColor: '#9fa8da',
            },
          ]
        },
        options: {
          legend: {
            display: false,
          },
          scales: {
            xAxes: [{
              display: true,
              scaleLabel: {
                display: true,
                labelString: 'Past Seconds'
              }
            }],
            yAxes: [{
              display: true,
              scaleLabel: {
                display: true,
                labelString: 'MBytes/s'
              }
            }]
          }
        }
    });
    function initialCharts(){
      poolChart.data.datasets[0].data = [0, 0];
      cellChart.data.datasets[0].data = [0, 0];
      instanceChart.data.datasets[0].data = [0, 0, 0, 0];
      diskChart.data.datasets[0].data = [0, 0];
      for(var i = 0; i < 6;i++){
        cpuChart.data.datasets[0].data.push(0);
        cpuChart.data.datasets[1].data.push(0);
      }
      cpuChart.options.scales.yAxes[0].ticks = {
          min: 0,
          max: 100,
          stepSize: 20
      };
      for(var i = 0; i < 6;i++){
        memoryChart.data.datasets[0].data.push(0);
        memoryChart.data.datasets[1].data.push(0);
      }
      memoryChart.options.scales.yAxes[0].ticks = {
          min: 0,
          max: 100,
          stepSize: 20
      };

      for(var i = 0; i < 9;i++){
        ioChart.data.datasets.forEach((dataset) => {
          dataset.data.push(0);
        });
      }
      ioChart.options.scales.yAxes[0].ticks = {
          min: 0,
          max: 10,
          stepSize: 2
      };
      poolChart.update();
      cellChart.update();
      instanceChart.update();
      diskChart.update();
      cpuChart.update();
      memoryChart.update();
      ioChart.update();
    }

    function updateDashboard(){
      $.getJSON("/compute_zone_status/", function(result){
        if (0 != result['error_code']) {
            M.toast({html: 'update dashboard fail:' + result['message']});
            return;
        }
        //success
        var status = result['data'];
        if (!status['start_time']){
          M.toast({html: 'no start time available'});
          return;
        }
        var startTime = new Date(status['start_time']);
        var now = new Date();
        var elapsedSeconds = Math.floor((now.getTime() - startTime.getTime())/1000);
        var elapsedDays = Math.floor(elapsedSeconds/(24*3600));
        elapsedSeconds -= elapsedDays*24*3600;
        var elapsedHours = Math.floor(elapsedSeconds/3600);
        elapsedSeconds -= elapsedHours*3600;
        var elapsedMinutes = Math.floor(elapsedSeconds/60);
        elapsedSeconds -= elapsedMinutes*60;
        if (N.IsChinese()){
          $('#uptime').text('系统启动时间 ' + status['start_time'] + ', 已运行 ' + elapsedDays + ' 天 ' + elapsedHours + ' 小时 ' + elapsedMinutes + ' 分 ' + elapsedSeconds + ' 秒');
        }else{
          $('#uptime').text('System start at ' + status['start_time'] + ', Uptime: ' + elapsedDays + ' day, ' + elapsedHours + ' hour, ' + elapsedMinutes + ' min, ' + elapsedSeconds + ' secs');
        }


        poolChart.data.datasets[0].data = status['pools'];
        cellChart.data.datasets[0].data = status['cells'];
        instanceChart.data.datasets[0].data = status['instances'];
        var gib = 1 << 30;
        var availableDisk = Math.floor(status['available_disk'] * 100 / gib) / 100;
        var usedDisk = Math.floor((status['max_disk'] - status['available_disk']) * 100 / gib) / 100;
        diskChart.data.datasets[0].data = [availableDisk, usedDisk];
        //cpu
        cpuChart.data.datasets[0].data.shift();
        cpuChart.data.datasets[0].data.push(Math.floor(status['cpu_usage'] * status['max_cpu'] )/100);
        cpuChart.data.datasets[1].data.shift();
        cpuChart.data.datasets[1].data.push(Math.floor(( 100 - status['cpu_usage']) * status['max_cpu'])/100);
        cpuChart.options.scales.yAxes[0].ticks = {
            max: status['max_cpu'],
            stepSize: status['max_cpu'] / 4
        };
        var used_memory = Math.floor((status['max_memory'] - status['available_memory']) * 100 / gib) / 100;
        var max_memory = Math.round(status['max_memory']  / gib) ;
        var available_memory = Math.floor(status['available_memory'] * 100 / gib) / 100;
        //memory
        memoryChart.data.datasets[0].data.shift();
        memoryChart.data.datasets[0].data.push(used_memory);
        memoryChart.data.datasets[1].data.shift();
        memoryChart.data.datasets[1].data.push(available_memory);
        memoryChart.options.scales.yAxes[0].ticks = {
            max: max_memory,
            stepSize: max_memory / 4
        };
        var mib = 1 << 20;
        var speed = [Math.floor(status['read_speed'] * 100 / mib) / 100, Math.floor(status['write_speed'] * 100 / mib) / 100,
            Math.floor(status['receive_speed'] * 100 / mib) / 100, Math.floor(status['send_speed'] * 100 / mib) / 100 ]

        for(var i = 0; i < 4 ; i++)    {
          ioChart.data.datasets[i].data.shift();
          ioChart.data.datasets[i].data.push(speed[i]);
        }
        poolChart.update();
        cellChart.update();
        instanceChart.update();
        diskChart.update();
        cpuChart.update();
        memoryChart.update();
        ioChart.update();
      });
    }

    $(function(){
      initialCharts();
      updateDashboard();
      setInterval(updateDashboard, 2000);
    });


  </script>
  </body>
</html>
